package implementation.server;

import java.util.logging.Logger;

import implementation.shared.IPacket;

import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.group.ChannelGroup;

public class ServerChannelHandler extends SimpleChannelHandler {
	
	private ISession _session;
	private ISessionManager _sessionManager;
	private ChannelGroup _group;
	private Logger _logger;
	
	public ServerChannelHandler(ISessionManager sessionManager, ChannelGroup group) {
		super();
		this._sessionManager = sessionManager;
		this._group = group;
		this._logger = Logger.getLogger(this.getClass().toString());
	}
	
	
	@Override
	public void channelConnected(ChannelHandlerContext context, ChannelStateEvent e) throws Exception {
		
		this._session = this._sessionManager.createSession(new Connection(e.getChannel()));
		this._group.add(e.getChannel());
		this._logger.info("client connected: "+e.getChannel().getId()+" "+e.getChannel().getRemoteAddress());
	}
	
	@Override
	public void channelDisconnected(ChannelHandlerContext context, ChannelStateEvent e) {
		this._session.close();
	}
	
	@Override
	public void messageReceived(ChannelHandlerContext context, MessageEvent e) {
		IPacket packet = (IPacket)e.getMessage();
		IPacket answer = this._session.handlePacket(packet);
		if (answer != null) {
			e.getChannel().write(answer);
		}
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext context, ExceptionEvent e) {
		e.getCause().printStackTrace();
	}
}